import hashlib
import json


class AIDcode:

    def structured_summary(df):
        """生成结构化数据摘要"""
        return {
            "metadata": {
                "shape": df.shape,
                "columns": df.columns.tolist(),
                "dtypes": df.dtypes.astype(str).to_dict()
            },
            "statistics": {
                col: {
                    "unique": df[col].nunique(),
                    "top_values": df[col].value_counts().head(3).to_dict(),
                    "missing": df[col].isnull().sum()
                } for col in df.columns
            },
            "samples": df.sample(min(3, len(df))).to_dict(orient="records")
        }


class LightEncoder:
    def __init__(self, min_length=8):
        self.mapping = {}  # 编码映射表
        self.min_length = min_length  # 需要压缩的最小长度

    def auto_encode(self, s):
        """ 自动生成可逆短编码 """

        # # 使用示例
        # encoder = LightEncoder(min_length=8)
        # data = ["North American Regional Sales Department", "IT", "R&D_Center"]
        # encoded = [encoder.auto_encode(x) for x in data]
        # print(encoded)  # ['C4A3B7', 'IT', 'R&D_Center']

        if len(str(s)) <= self.min_length:
            return s

        # 生成唯一短哈希（前6位）
        hash_code = hashlib.md5(str(s).encode()).hexdigest()[:6]
        short_code = f"C{hash_code.upper()}"  # 添加前缀防止数字开头

        # 维护双向映射
        self.mapping[short_code] = s
        return short_code


class LightDecoder:
    def __init__(self, mapping):
        self.mapping = mapping

    def decode_text(self, text):
        """ 支持混合文本中嵌入编码的格式 """
        import re
        pattern = r'C[A-F0-9]{5}'  # 匹配编码格式

        # # 使用示例
        # decoder = LightDecoder(encoder.mapping)
        # model_output = "C4A3B7部门Q1增长最高"
        # print(decoder.decode_text(model_output))
        # # 输出：北美区域销售部部门Q1增长最高

        def replace_code(match):
            code = match.group()
            return f"{self.mapping.get(code, code)}"

        return re.sub(pattern, replace_code, text)
